<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <DeptTree class="deptTree" @select="handleSelect" />
    <div style="width: calc(100% - 248px)">
      <BasicTable @register="registerTable" :searchInfo="searchInfo" style="width: 100%">
        <template #tableTitle>
          <a-button
            type="primary"
            @click="handleCreate()"
            class="action-button"
            v-if="checkAuth('ADD-USER')"
          >
            + 新增用户
          </a-button>
          <BasicImport
            @success="handleImport"
            :api="uploadUserApi"
            :tempApi="tempUserApi"
            v-if="checkAuth('TO-CHANNEL-USER')"
          >
            <a-button style="border-radius: 4px; margin-right: 16px"> 导入 </a-button>
          </BasicImport>
          <HExportColumn
            :colunm-api="getColumnsTitleList"
            :api="exportCustomExport"
            style="border-radius: 4px; margin-right: 16px"
            :beforeOpenModelCallback="handleBeforeOpenModal"
            :params="{ query }"
            v-if="checkAuth('EXPORT-USER')"
          />
          <!-- <a-button @click="handleExport" class="action-button" v-if="checkAuth('EXPORT-USER')">
            导出
          </a-button> -->
          <a-button
            @click="handleResetPwd"
            class="action-button"
            v-if="checkAuth('RESET-PADDWORD')"
          >
            重置密码
          </a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'action'">
            <TableAction
              :actions="[
                {
                  ifShow: checkAuth('EDIT-USER'),
                  label: '编辑',
                  onClick: handleEdit.bind(null, record),
                },
                {
                  ifShow: checkAuth('DELETE-USER'),
                  label: '删除',
                  onClick: ($event) => $event.stopPropagation(),
                  popConfirm: {
                    title: '是否确认删除',
                    placement: 'left',
                    confirm: handleDelete.bind(null, record),
                  },
                },
              ]"
            />
          </template>
        </template>
      </BasicTable>
    </div>

    <AccountModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref } from 'vue';
  import { HExportColumn } from '/@/components/HExportColumn';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import { BasicImport } from '/@/components/ImportButton';
  import AccountModal from './AccountModal.vue';
  import DeptTree from './DeptTree.vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { downloadByData } from '/@/utils/file/download';
  import { useModal } from '/@/components/Modal';
  import { useGo } from '/@/hooks/web/usePage';

  import { setTableEmptyHeight } from '/@/utils';

  import { columns, searchFormSchema } from './account.data';
  import { getBtnAuth, checkAuth } from '/@/utils/cutomPageBtnAuth/index';
  import { useRoute } from 'vue-router';
  import {
    // getUserListByPage,
    deleteUserApi,
    exportUserApi,
    uploadUserApi,
    tempUserApi,
    putUserResetApi,
    getColumnsTitleList,
    exportCustomExport,
    getUserListByPageV2,
  } from '/@/api/admin/user';

  export default defineComponent({
    name: 'SystemAccount',
    components: {
      BasicTable,
      PageWrapper,
      DeptTree,
      AccountModal,
      TableAction,
      BasicImport,
      HExportColumn,
    },
    setup() {
      const go = useGo();
      const route = useRoute();
      const query = ref({});

      const { createMessage, createSuccessModal } = useMessage();

      const [registerModal, { openModal }] = useModal();
      const searchInfo = reactive<Recordable>({});
      const [registerTable, { reload, getRowSelection, getForm }] = useTable({
        title: '岗位分配',
        api: getUserListByPageV2,
        rowSelection: {
          type: 'checkbox',
        },
        rowKey: 'userId',
        columns,
        formConfig: {
          labelWidth: 60,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
        },
        ellipsis: false,
        immediate: false,
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        handleSearchInfoFn(info) {
          return info;
        },
        actionColumn: {
          title: '操作',
          dataIndex: 'action',
          width: 120,
          fixed: 'right',
          // slots: { customRender: 'action' },
        },
        indexColumnProps: {
          width: 60,
          align: 'left',
        },
        afterFetch(res) {
          setTableEmptyHeight(res);
        },
      });

      getBtnAuth(route, reload);

      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }

      function handleEdit(record: Recordable, $event) {
        $event.stopPropagation();
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      async function handleDelete(record: Recordable, $event) {
        $event.stopPropagation();
        await deleteUserApi(record.userId);
        createMessage.success('操作成功');
        reload();
      }

      function handleSuccess() {
        reload();
      }

      function handleSelect(deptId = '') {
        searchInfo.deptId = deptId;
        reload();
      }

      function handleView(record: Recordable) {
        go('/system/account_detail/' + record.id);
      }
      function handleImport() {
        createMessage.success('操作成功');
        reload();
      }
      async function handleExport() {
        const file = await exportUserApi();
        downloadByData(file, `user_${Date.now()}.xlsx`);
      }
      // 弹窗打开之前获取搜索区域内容传值到导出组件
      const handleBeforeOpenModal = () => {
        const { getFieldsValue } = getForm();
        query.value = getFieldsValue();
      };

      async function handleResetPwd() {
        console.log('getRowSelection', getRowSelection());
        let selectedRowKeys = getRowSelection().selectedRowKeys!;
        if (selectedRowKeys && !selectedRowKeys.length) {
          createMessage.warning('请选择用户');
          return;
        }
        const params = {
          ids: [...selectedRowKeys],
        };
        const res: any = await putUserResetApi(params);
        createSuccessModal({
          title: '提示',
          content: `重置密码成功,新密码为${res}`,
        });
      }

      return {
        registerTable,
        registerModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleSelect,
        handleView,
        searchInfo,
        handleImport,
        handleExport,
        uploadUserApi,
        tempUserApi,
        handleResetPwd,
        checkAuth,
        getColumnsTitleList,
        exportCustomExport,
        handleBeforeOpenModal,
        query,
      };
    },
  });
</script>

<style scoped lang="less">
  .deptTree {
    width: 248px;
    padding-top: 7px;
  }

  :deep(.vben-basic-table-form-container) {
    padding-left: 0;
  }

  :deep(.vben-basic-table .ant-table-wrapper) {
    padding-left: 16px;
    padding-top: 16px;
  }

  :deep(.vben-basic-table .ant-table-wrapper .ant-table-title) {
    padding-bottom: 16px !important;
  }

  :deep(.vben-tree) {
    border-right: 1px solid #e9e9e9;
  }

  :deep(.vben-tree-header) {
    border-bottom: none;
  }

  .action-button {
    border-radius: 4px;

    &:not(:last-of-type) {
      margin-right: 16px !important;
    }
  }

  :deep(.ant-table-tbody) {
    > tr.ant-table-row-selected > td {
      background-color: #f8f8f8;
    }
  }
</style>
